<template>
  <div>
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="90%">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-divider content-position="left"><span class="divider-css">▶消耗品基本信息◀</span></el-divider>
        <el-row>
          <!-- 开始用 el-col 包裹每个 el-form-item -->
          <el-col :span="6">
            <el-form-item label="消耗品类别" prop="materialStyle">
              <el-select v-model="form.materialStyle" placeholder="请选择消耗品产品类别"
                         @change="selectChange($event, 'MATERIAL_STYLE', 'materialStyleName')">
                <el-option
                  v-for="dict in dictDataMap['MATERIAL_STYLE']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="全成本分类" prop="htcaClass">
              <el-select v-model="form.htcaClass" placeholder="全成本分类"
                         @change="selectChange($event, 'COST_CLASS', 'htcaClassName')">
                <el-option
                  v-for="dict in dictDataMap['COST_CLASS']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="型号" prop="materialModel">
              <el-input v-model="form.materialModel" placeholder="请输入型号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="材质" prop="materialIndicator">
              <el-input v-model="form.materialIndicator" placeholder="请输入材质"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="消耗品名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入消耗品名称" @blur="materialNameBlue"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="消耗品别名" prop="materialNameAlias">
              <el-input v-model="form.materialNameAlias" placeholder="请输入消耗品别名"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="消耗品拼音码" prop="materialInput">
              <el-input v-model="form.materialInput" placeholder="请输入消耗品拼音码"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="消耗品编码" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="请输入消耗品编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="条形码" prop="barCode">
              <el-input v-model="form.barCode" placeholder="请输入条形码"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="基本规格" prop="minNum">
              <el-input v-model="form.minNum" placeholder="请输入数量" style="width: 30%"
                        :disabled="form.isExistStock"/>
              <el-select ref="minUnits" v-model="form.minUnits" v-keyupEnter="{ index: 0, name: 'minUnits' }"
                         :disabled="form.isExistStock"
                         default-first-option
                         filterable placeholder="最小单位" prop="minUnits"
                         @change="chargeInput($event,'minUnits', 'spec_unit', 'minUnitsName')"
                         style="width: 30%">
                <el-option v-for="dict in dictDataMap['spec_unit']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
              <el-input v-model="form.minSpec" :disabled="form.isExistStock" style="width: 40%"
                        placeholder="请输入规格"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="包装规格" prop="packageSpec">
              <el-input v-model="form.packageNum" placeholder="包装数量" :disabled="form.isExistStock"
                        style="width: 30%"/>
              <el-select ref="packageUnit" v-model="form.packageUnit" v-keyupEnter="{ index: 0, name: 'packageUnit' }"
                         :disabled="form.isExistStock"
                         default-first-option
                         filterable placeholder="包装单位" prop="packageUnit"
                         @change="chargeInput($event,'packageUnit', 'spec_unit', 'packageUnitName')"
                         style="width: 30%">
                <el-option v-for="dict in dictDataMap['spec_unit']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
              <el-input v-model="form.packageSpec" :disabled="form.isExistStock"
                        style="width: 40%" placeholder="包装规格"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="供应商" prop="supplierId">
              <material-supplier :id="form.supplierName" ref="supplierName" v-keyupEnter="{ index: 0, name: 'supplierName' }"
                        :placeholder="'请选择供应商'"
                        :tabindex="'11'"
                        style="width: 100%; float: left; display: inline"
                        @supplierChange="supplierChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="厂家" prop="firmId">
              <material-producer :id="form.firmName" ref="firmName" v-keyupEnter="{ index: 0, name: 'firmName' }"
                        :placeholder="'请选择生产厂商'"
                        :tabindex="'11'"
                        style="width: 100%; float: left; display: inline"
                        @producerChange="producerChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="耗材来源" prop="materialSource">
              <el-select v-model="form.materialSource" placeholder="请选择耗材来源"
                         @change="selectChange($event, 'material_source', 'materialSourceName')">
                <el-option
                  v-for="dict in dictDataMap['material_source']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="批准文号" prop="passNo">
              <el-input v-model="form.passNo" placeholder="请输入批准文号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品编号" prop="materialItemNo">
              <el-input v-model="form.materialItemNo" placeholder="请输入产品编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品备案号" prop="goodsRecordNo">
              <el-input v-model="form.goodsRecordNo" placeholder="请输入产品备案号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产许可证号" prop="produceLicenseNo">
              <el-input v-model="form.produceLicenseNo" placeholder="请输入生产许可证号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="卫生许可证号" prop="hygieneLicenseNo">
              <el-input v-model="form.hygieneLicenseNo" placeholder="请输入卫生许可证号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品技术要求编号" prop="technologyRequireNo">
              <el-input v-model="form.technologyRequireNo" placeholder="请输入产品技术要求编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="医疗器械注册证号" prop="medicalDeviceRegistNo">
              <el-input v-model="form.medicalDeviceRegistNo" placeholder="请输入医疗器械注册证号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="执行标准" prop="executeStandardNo">
              <el-input v-model="form.executeStandardNo" placeholder="请输入执行标准"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="招采标志" prop="isPurchase">
              <el-radio-group v-model="form.isPurchase">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                          :value="dict.dictValue">{{
                  dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="自费或医保" prop="zfOrYb">
              <el-radio-group ref="zfOrYb" v-model="form.zfOrYb">
                <el-radio v-for="dict in dictDataMap['is_medical_insurance']" :key="dict.dictValue"
                          :tabindex="'12'"
                          :value="dict.dictValue">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="GMP标识" prop="gmp">
              <el-radio-group v-model="form.gmp">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                          :value="dict.dictValue">{{
                  dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="国家医保名称" prop="countryYbName">
              <el-input v-model="form.countryYbName" placeholder="请输入国家医保名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="国家医保编码" prop="countryYbCode">
              <el-input v-model="form.countryYbCode" placeholder="请输入国家医保编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="门诊住院" prop="outorinp">
              <el-select v-model="form.outorinp" placeholder="请选择门诊住院">
                <el-option
                  v-for="dict in dictDataMap['clinic_or_visit']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注信息" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请输入备注信息"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备用字段1" prop="remarks1">
              <el-input v-model="form.remarks1" placeholder="请输入备用字段1"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备用字段2" prop="remarks2">
              <el-input v-model="form.remarks2" placeholder="请输入备用字段2"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备用字段3" prop="remarks3">
              <el-input v-model="form.remarks3" placeholder="请输入备用字段3"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备用字段4" prop="remarks4">
              <el-input v-model="form.remarks4" placeholder="请输入备用字段4"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="" prop="isPrice">
              <el-checkbox v-model="isPrice" label="生成价表" :disabled="form.isExistStock"
                @change="isPriceChange"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left"><span class="divider-css">▶消耗品价格◀</span></el-divider>
        <el-row>
          <el-table :key="tableTime" ref="table" :border="true" :data="form.materialPriceList"
                    :header-cell-style="$headerCellStyle" :stripe="true"
                    header-cell-class-name="requiredClass"
                    highlight-current-row style="width: 100%">
            <el-table-column :align="'center'" label="消耗品编码" prop="materialCode">
              <template #default="scope">
                <el-form-item :prop="'materialPriceList.' + scope.$index + '.materialCode'"
                              :rules="rules.materialCode"
                              class="table-form-margin">
                  <el-input v-model="scope.row.materialCode" disabled></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="单位" prop="units" width="80px">
              <template #default="scope">
                <el-form-item class="table-form-margin">
                  <el-tag v-if="!scope.row.units">无</el-tag>
                  <dict-data-tag v-else :options="dictDataMap['spec_unit']"
                                 :value="scope.row.units"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="规格" prop="packageSpec">
              <template #default="scope">
                <el-form-item :prop="'materialPriceList.' + scope.$index + '.packageSpec'"
                              :rules="rules.packageSpec"
                              class="table-form-margin">
                  <el-input v-model="scope.row.packageSpec" disabled></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="进价(元)" prop="tradePrice" width="90px">
              <template #default="scope">
                <el-form-item :prop="'materialPriceList.' + scope.$index + '.tradePrice'"
                              :rules="rules.tradePrice"
                              class="table-form-margin">
                  <el-input v-model="scope.row.tradePrice"
                            v-keyupEnter="{ index: scope.$index, name: 'tradePrice' }"
                            :disabled="scope.row.packSize === '1' || form.isExistStock"
                            @blur="tradePriceBlue(scope.$index)"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="比例" prop="ratio" width="100px">
              <template #default="scope">
                <el-form-item :prop="'materialPriceList.' + scope.$index + '.ratio'"
                              class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.ratio"
                             v-keyupEnter="{ index: scope.$index, name: 'ratio' }"
                             :disabled="scope.row.packSize === '1' || form.isExistStock"
                             filterable
                             placeholder="请选择比例" style="width: 100%"
                             @change="tradePriceBlue(scope.$index)"
                             @keyup.enter.native="$changeFocus('passNo')">
                    <el-option v-for="dict in dictDataMap['price_ratio']" :key="dict.dictValue"
                               :label="dict.dictLabel"
                               :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="售价(元)" prop="retailPrice" width="100px">
              <template #default="scope">
                <el-form-item :prop="'materialPriceList.' + scope.$index + '.retailPrice'"
                              :rules="rules.retailPrice"
                              class="table-form-margin">
                  <el-input v-model="scope.row.retailPrice"
                            v-keyupEnter="{ index: scope.$index, name: 'retailPrice' }"
                            :disabled="scope.row.packSize === '1' || form.isExistStock"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="门诊费用分类" prop="classOnRcpt" width="100">
              <template #default="scope">
                <el-form-item :prop="'materialPriceList.' + scope.$index + '.classOnRcpt'"
                              :rules="rules.classOnRcpt"
                              class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.classOnRcpt"
                             v-keyupEnter="{ index: scope.$index, name: 'classOnRcpt' }"
                             filterable
                             placeholder="请选择"
                             style="width: 100%">
                    <el-option v-for="dict in dictDataMap['outp_rcpt_fee_dict']"
                               :key="dict.dictValue"
                               :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="住院费用分类" prop="classOnInp" width="100">
              <template #default="scope">
                <el-form-item :prop="'materialPriceList.' + scope.$index + '.classOnInp'"
                              :rules="rules.classOnInp"
                              class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.classOnInp"
                             v-keyupEnter="{ index: scope.$index, name: 'classOnInp' }"
                             filterable placeholder="请选择"
                             style="width: 100%">
                    <el-option v-for="dict in dictDataMap['inp_rcpt_fee_dict']"
                               :key="dict.dictValue"
                               :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="核算项目分类" prop="classOnReckoning" width="100">
              <template #default="scope">
                <el-form-item :prop="'materialPriceList.' + scope.$index + '.classOnReckoning'"
                              :rules="rules.classOnReckoning" class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.classOnReckoning"
                             v-keyupEnter="{ index: scope.$index, name: 'classOnReckoning' }"
                             filterable
                             placeholder="请选择" style="width: 100%"
                             @keyup.enter.native="$changeFocus('passNo')">
                    <el-option v-for="dict in dictDataMap['reck_item_class_dict']"
                               :key="dict.dictValue"
                               :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="会计科目" prop="subjCode" width="100">
              <template #default="scope">
                <el-form-item :prop="'materialPriceList.' + scope.$index + '.subjCode'"
                              :rules="rules.subjCode"
                              class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.subjCode"
                             v-keyupEnter="{ index: scope.$index, name: 'subjCode' }" filterable
                             placeholder="请选择"
                             style="width: 100%">
                    <el-option v-for="dict in dictDataMap['tally_subject_dict']"
                               :key="dict.dictValue"
                               :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="病案首页分类" prop="classOnMr" width="100">
              <template #default="scope">
                <el-form-item :prop="'materialPriceList.' + scope.$index + '.classOnMr'"
                              :rules="rules.classOnMr"
                              class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.classOnMr"
                             v-keyupEnter="{ index: scope.$index, name: 'classOnMr' }" filterable
                             placeholder="请选择"
                             style="width: 100%">
                    <el-option v-for="dict in dictDataMap['mr_fee_class_dict']"
                               :key="dict.dictValue"
                               :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="启用日期" prop="startDate" width="200">
              <template #default="scope">
                <el-form-item :prop="'materialPriceList.' + scope.$index + '.startDate'"
                              :rules="rules.startDate"
                              class="table-form-margin">
                  <el-date-picker v-model="scope.row.startDate" clearable placeholder="请选择起用日期"
                                  style="width: 100%"
                                  type="datetime" value-format="YYYY-MM-DD HH:mm:ss">
                  </el-date-picker>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" label="操作"
                             width="150">
              <template #default="scope">
                <el-button v-if="scope.row.packSize !== '1'" type="primary"
                           @click="splitBigPackageSpec(scope.row)">
                  <template #icon>
                    <i-ep-edit/>
                  </template>
                  拆分【大包装】
                </el-button>
                <el-button v-if="!form.isExistStock && scope.row.packSize === '1'"
                           type="danger" @click="deleteSmallPackageSpec(scope.$index)">
                  <template #icon>
                    <i-ep-edit/>
                  </template>
                  删除【小包装】
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {
  addMaterialInfo,
  getMaterialInfo,
  updateMaterialInfo,
  getAutoMaterialCode
} from "@/api/material/materialInfo";

import {useDictStoreHook} from "@/store/modules/dict";
import {tradePriceV} from "@/utils/myRules";
import {firstLetterResult} from "@/utils/pinyin";
import {useUserStoreHook} from "@/store/modules/user"

const emits = defineEmits(['getListParent'])
const {proxy} = getCurrentInstance() as any;
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('clinic_or_visit', 'material_source', 'COST_CLASS',
  'sys_yes_no', 'MATERIAL_STYLE', 'is_medical_insurance', 'spec_unit', 'mr_fee_class_dict', 'tally_subject_dict',
  'reck_item_class_dict', 'outp_rcpt_fee_dict', 'price_ratio', 'inp_rcpt_fee_dict'))

const formRef = ref();
const open = ref(false);
// 按钮loading
const buttonLoading = ref(false);
const tableTime = ref(new Date().getTime());
const title = ref();
const ids = ref();
const isPrice = ref(false);
const props = defineProps({
  // 机构id
  orgId: {
    type: String,
    default: "",
  },
});
const form = ref({
  // 价格list
  materialPriceList: [
    {
      packSize: "2",
      ratio: "1",
      tradePrice: 0,
      materialCode: "",
      units: "",
      unitsName: "",
      packageSpec: "",
      retailPrice: 0,
      classOnRcpt: "",
      classOnInp: "",
      classOnReckoning: "",
      subjCode: "",
      classOnMr: "",
      startDate: "",
      orgId: props.orgId,
      orgName: userInfo.orgName,
      supplySign: "Y",
    },
  ],
  materialClass: "I",
  materialStyle: "",
  materialStyleName: "",
  htcaClass: "",
  materialModel: "",
  materialIndicator: "",
  materialName: "",
  materialNameAlias: "",
  materialInput: "",
  materialCode: "",
  sysMaterialCode: "",
  barCode: "",
  minNum: undefined,
  minSpec: "",
  minUnits: "",
  minUnitsName: "",
  packageNum: undefined,
  packageSpec: "",
  packageUnit: "",
  packageUnitName: "",
  supplierId: "",
  supplierName: "",
  firmId: "",
  firmName: "",
  materialSource: "",
  passNo: "",
  materialItemNo: "",
  goodsRecordNo: "",
  produceLicenseNo: "",
  hygieneLicenseNo: "",
  technologyRequireNo: "",
  medicalDeviceRegistNo: "",
  executeStandardNo: "",
  testMethod: "",
  isPurchase: "N",
  zfOrYb: "1",
  gmp: "N",
  countryYbName: "",
  countryYbCode: "",
  outorinp: "2",
  materialImage: "",
  orgId: props.orgId,
  orgName: userInfo.orgName,
  remarks: "",
  remarks1: "",
  remarks2: "",
  remarks3: "",
  remarks4: "",
  materialSourceName: "",
  isExistStock: false,
})

const rules = ref({
    materialStyle: [{required: true, message: "消耗品产品类别", trigger: "change"}],
    materialStyleName: [{required: true, message: "消耗品产品类别名称", trigger: "change"}],
    materialName: [{required: true, message: "消耗品名称不能为空", trigger: "blur"}],
    materialCode: [{required: true, message: "消耗品编码不能为空", trigger: "blur"}],
    sysMaterialCode: [{required: true, message: "消耗品编码不能为空", trigger: "blur"}],
    materialInput: [{required: true, message: "消耗品拼音码不能为空", trigger: "blur"}],
    minNum: [{required: true, message: "基本数量不能为空", trigger: "blur"}],
    minSpec: [{required: true, message: "规格不能为空", trigger: "blur"}],
    minUnits: [{required: true, message: "单位不能为空", trigger: "blur"}],
    minUnitsName: [{required: true, message: "单位名称不能为空", trigger: "blur"}],
    packageNum: [{required: true, message: "包装数量不能为空", trigger: "blur"}],
    packageSpec: [{required: true, message: "包装规格不能为空", trigger: "blur"}],
    packageUnit: [{required: true, message: "包装单位不能为空", trigger: "blur"}],
    packageUnitName: [{required: true, message: "包装单位名称不能为空", trigger: "blur"}],
    firmId: [{required: true, message: "厂家标识不能为空", trigger: "blur"}],
    firmName: [{required: true, message: "厂家名称不能为空", trigger: "blur"}],
    outorinp: [{required: true, message: "门诊住院", trigger: "change"}],
    orgId: [{required: true, message: "机构不能为空", trigger: "blur"}],
    tradePrice: [{required: true, validator: tradePriceV, trigger: "blur"}],
    retailPrice: [{required: true, message: "不能为空", trigger: "blur"}],
    startDate: [{required: true, message: "起用日期不能为空", trigger: "blur"}],
    classOnRcpt: [{required: true, message: "不能为空", trigger: "change"}],
    classOnInp: [{required: true, message: "不能为空", trigger: "change"}],
    classOnReckoning: [{required: true, message: "不能为空", trigger: "change"}],
    subjCode: [{required: true, message: "不能为空", trigger: "change"}],
    classOnMr: [{required: true, message: "不能为空", trigger: "change"}],
  }
)

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.materialInfoId != null) {
        if (form.value.materialPriceList && form.value.materialPriceList.length > 0) {
          form.value.isCheck = '1';
        } else {
          form.value.isCheck = '0';
        }
        console.log(form.value);
        updateMaterialInfo(form.value).then((response: any) => {
          ElMessage.success("修改成功");
          open.value = false;
          emits('getListParent')
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        if (form.value.materialPriceList && form.value.materialPriceList.length > 0) {
          form.value.isCheck = '1';
        } else {
          form.value.isCheck = '0';
        }
        console.log(form.value);

        addMaterialInfo(form.value).then((response: any) => {
          ElMessage.success("新增成功");
          open.value = false;
          emits('getListParent')
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.materialPriceList = [
    {
      packSize: "2",
      ratio: "1",
      tradePrice: 0,
      materialCode: "",
      units: "",
      unitsName: "",
      packageSpec: "",
      retailPrice: 0,
      classOnRcpt: "",
      classOnInp: "",
      classOnReckoning: "",
      subjCode: "",
      classOnMr: "",
      startDate: "",
      orgId: props.orgId,
      orgName: userInfo.orgName,
      supplySign: "Y",
    },
  ];
  tableTime.value = new Date().getTime();
  open.value = true;
  title.value = "添加消耗品字典基本信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const materialInfoId = row.materialInfoId || ids.value;
  getMaterialInfo(materialInfoId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改消耗品字典基本信息";
    if(form.value.materialPriceList && form.value.materialPriceList.length > 0){
      isPrice.value = true;
    }else{
      isPrice.value = false;
    }
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    materialClass: "I",
    materialStyle: "",
    materialStyleName: "",
    htcaClass: "",
    materialModel: "",
    materialIndicator: "",
    materialName: "",
    materialNameAlias: "",
    materialInput: "",
    materialCode: "",
    sysMaterialCode: "",
    barCode: "",
    minSpec: "",
    minUnits: "",
    minUnitsName: "",
    packageSpec: "",
    packageUnit: "",
    packageUnitName: "",
    supplierId: "",
    supplierName: "",
    firmId: "",
    firmName: "",
    materialSource: "",
    passNo: "",
    materialItemNo: "",
    goodsRecordNo: "",
    produceLicenseNo: "",
    hygieneLicenseNo: "",
    technologyRequireNo: "",
    medicalDeviceRegistNo: "",
    executeStandardNo: "",
    testMethod: "",
    isPurchase: "N",
    zfOrYb: "1",
    gmp: "N",
    countryYbName: "",
    countryYbCode: "",
    outorinp: "2",
    orgId: props.orgId,
    orgName: userInfo.orgName,
    remarks: "",
    remarks1: "",
    remarks2: "",
    remarks3: "",
    remarks4: "",
    materialSourceName: "",
    isExistStock: false,
  }
}

/** 拆分【大包装】 */
function splitBigPackageSpec(_obj) {
  if (!form.value.materialCode || !form.value.materialName || !form.value.packageSpec) {
    return ElMessage.error("消耗品信息不完整，请填写完整后再拆分");
  }
  let index = form.value.materialPriceList.findIndex((item) => {
    return item.packSize === "1";
  });
  if (index <= -1) {
    let bigTr = form.value.materialPriceList[0];
    let packageSpec = bigTr.packageSpec;
    // let specArray = packageSpec.split("*");
    let smallTr = {
      packSize: "1",
      ratio: bigTr.ratio,
      materialInfo: bigTr.materialInfo,
      tradePrice: (bigTr.tradePrice / Number(form.value.packageNum)).toFixed(4),
      materialCode: bigTr.materialCode + "x",
      units: form.value.minUnits,
      unitsName: form.value.minUnitsName,
      packageSpec: form.value.minSpec,
      retailPrice: (bigTr.retailPrice / Number(form.value.packageNum)).toFixed(4),
      classOnRcpt: bigTr.classOnRcpt,
      classOnInp: bigTr.classOnInp,
      classOnReckoning: bigTr.classOnReckoning,
      subjCode: bigTr.subjCode,
      classOnMr: bigTr.classOnMr,
      startDate: "",
      orgId: props.orgId,
      orgName: userInfo.orgName,
      supplySign: "Y",
    };
    form.value.materialPriceList.push(smallTr);
  } else {
    return ElMessage.error("此药品已拆分，不能再次拆分");
  }
}

/** 删除【小包装】 */
function deleteSmallPackageSpec(index) {
  form.value.materialPriceList.splice(index, 1);
  //@ts-ignore
  formRef.validate();
}

/**
 * 字典select 点击事件
 * @param value select选中值
 * @param type 字典 type
 * @param name 字典对应的属性名称
 */
function selectChange(value, type, name) {
  let dictInfo: any = {};
  if (type) {
    let dictIndex = dictDataMap.value[type].findIndex((item) => {
      return item.value || item.dictValue === value;
    });
    if (dictIndex > -1) {
      dictInfo = dictDataMap.value[type][dictIndex];
      form.value[name] = dictInfo.label || dictInfo.dictLabel;
    }
  }
  if (type === 'MATERIAL_STYLE' || type === 'COST_CLASS') {
    getAutoMaterialCodeFun();
  }
}

/*
 * 自动计算包装单位等数据
 * @param event 选中值
 * @param type select 类别
 * @param dictType 字典类型 （设置字典翻译名称时使用）
 * @param name 字典对应name （设置字典翻译名称时使用）
 */
function chargeInput(event, type, dictType, name) {
  selectChange(event, dictType, name);
  nextTick(() => {
    console.log("type", type);
    console.log("dictType", dictType);
    console.log("name", name);
    if (type === "minUnits") {
      form.value.minSpec = form.value.minNum + form.value.minUnitsName;
    }
    if (type === "packageUnit") {
      form.value.packageSpec = form.value.minSpec + "*" + form.value.packageNum + "/" + form.value.packageUnitName;
      form.value.materialPriceList[0].packageSpec = form.value.packageSpec;
      form.value.materialPriceList[0].units = form.value.packageUnit;
      form.value.materialPriceList[0].unitsName = form.value.packageUnitName;
    }
    tableTime.value = new Date().getTime();
  });
}

/** 生产厂商点击事件 */
function producerChange(obj) { 
  form.value.firmId = obj.supplierId;
  form.value.firmName = obj.supplierName;
}

/** 供应商点击事件 */
function supplierChange(obj) { 
  form.value.supplierId = obj.supplierId;
  form.value.supplierName = obj.supplierName;
}

/**
 * 消耗品名称焦点消失
 */
function materialNameBlue() {
  const materialName: string = form.value.materialName;
  if (materialName) {
    // 根据药品名称获取药品别名
    form.value.materialNameAlias = materialName;
  }
  materialNameAliasBlue();
}


/**消耗品别名焦点消失 */
function materialNameAliasBlue() {
  materialInputSplicing()
}

/**
 * 通过消耗品名称和别名拼接拼音码
 */
function materialInputSplicing() {
  if (form.value.materialName) {
    form.value.materialInput = firstLetterResult(form.value.materialName);
  }
//   if (form.value.materialNameAlias) {
//     form.value.materialInput = form.value.materialInput + "," + firstLetterResult(form.value.materialNameAlias);
//   }
  if (!form.value.materialName && !form.value.materialNameAlias) {
    form.value.materialInput = "";
    form.value.materialNameAlias = "";
  }
}

/**
 * 获取消耗品编码
 */
function getAutoMaterialCodeFun() {
  const params = {
    orgId: props.orgId,
    materialStyle: form.value.materialStyle,
    htcaClass: form.value.htcaClass
  }
  getAutoMaterialCode(params).then((res: any) => {
    form.value.materialCode = res.data
    form.value.sysMaterialCode = form.value.materialCode
    form.value.materialPriceList[0].materialCode = form.value.materialCode;
  })
}

/** 进价焦点消失 、计算售价*/
function tradePriceBlue(index) {
  // 进价
  let tradePrice = form.value.materialPriceList[index].tradePrice;
  if (tradePrice) {
    // 获取点击行的行号index
    const ratioIndex = dictDataMap.value["price_ratio"].findIndex((item) => {
      return item.value || item.dictValue === form.value.materialPriceList[index].ratio;
    });
    if (ratioIndex > -1) {
      const dictInfo = dictDataMap.value["price_ratio"][ratioIndex];

      // 设置本行售价
      form.value.materialPriceList[index].retailPrice = (
        tradePrice * Number(dictInfo.label || dictInfo.dictLabel)
      ).toFixed(4);
    }
    // 判断是否存在小包装数据，有的话同时修改
    const smallTrIndex = form.value.materialPriceList.findIndex((item) => {
      return item.packSize === "1";
    });
    if (smallTrIndex > -1) {
      let smallTr = form.value.materialPriceList[smallTrIndex];
      smallTr.tradePrice = (tradePrice / Number(form.value.packageNum)).toFixed(4);
      smallTr.retailPrice = (
        form.value.materialPriceList[index].retailPrice / Number(form.value.packageNum)
      ).toFixed(4);
      smallTr.ratio = form.value.materialPriceList[index].ratio;
    }
  }
  tableTime.value = new Date().getTime();
}

function isPriceChange() {
  console.log(isPrice)
  if (isPrice.value){
    form.value.materialPriceList = [
      {
        packSize: "2",
        ratio: "1",
        tradePrice: 0,
        materialCode: form.value.materialCode,
        units: form.value.packageUnit,
        packageSpec: form.value.packageSpec,
        retailPrice: 0,
        classOnRcpt: "",
        classOnInp: "",
        classOnReckoning: "",
        subjCode: "",
        classOnMr: "",
        startDate: "",
        orgId: props.orgId,
        orgName: userInfo.orgName,
        supplySign: "Y",
      },
    ];
  }else {
    form.value.materialPriceList=[];
  }
}

defineExpose({
  handleAdd,
  handleUpdate,
});

</script>

<script lang="ts">
export default {
  name: "materialAdd",
};
</script>

<style scoped>
:deep(.el-col) {
  margin-bottom: -2px;
}

:deep(.el-divider__text.is-left) {
  font-weight: bold;
  font-size: 19px;
}

:deep(.el-table .cell) {
  padding-left: 5px;
  padding-right: 5px;
}

:deep(.table-form-margin > div) {
  margin-left: 0 !important;
}

:deep(.el-icon-plus) {
  margin-left: -2px;
}

:deep(.firm-name-div > div) {
  margin-bottom: 0 !important;
}

:deep(.el-divider--horizontal) {
  display: block;
  height: 1px;
  width: 100%;
  margin: 14px 0 20px 0;
}

:deep(.el-form-item__content) {
  display: block;
}

</style>
